package com.zwb.email;

import com.zwb.service.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @author 头发又黑又长
 * @Date 2022/9/10 18:13
 * @email zwb15083976291@163.com
 */
@Component
public class EmailSendUtil {

    @Autowired(required = false)
    private JavaMailSender mailSender;
    @Autowired(required = false)
    private MailProperties mailProperties;
    @Autowired(required = false)
    private TemplateEngine templateEngine;


    public void emailSend(String title, Employee employee, String templateName) throws MessagingException {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(msg);
        // 发件人
        messageHelper.setFrom(mailProperties.getUsername());
        // 收件人
        messageHelper.setTo(employee.getEmail());
        // 主题
        messageHelper.setSubject(title);
        // 时间
        messageHelper.setSentDate(new Date());
        //   邮件内容
        Context context = new Context();
        context.setVariable("name", employee.getName());
        context.setVariable("posName", employee.getPosition().getName());
        context.setVariable("joblevelName", employee.getJoblevel().getName());
        context.setVariable("departmentName", employee.getDepartment().getName());
        String text = templateEngine.process(templateName, context);
        messageHelper.setText(text, true);
        // 发送邮件
        mailSender.send(msg);
    }

}
